import datetime
import random

from flask_script import Manager
from flask_migrate import MigrateCommand, Migrate

from info import get_app, mysql_db, models  # 此处导入models为了数据迁移


# 参数选项： debug， release， test
from info.models import User

my_flask_app = get_app("debug")
manager = Manager(my_flask_app)

Migrate(my_flask_app, mysql_db)
manager.add_command("mysql_db", MigrateCommand)


@manager.option("-n", "-name", dest="name")
@manager.option("-p", "-password", dest="password")
def set_admin_user(name, password):
    if not all([name, password]):
        print("参数不足")
        return

    user = User()
    user.mobile = name
    user.nick_name = name
    user.password = password
    user.is_admin = True

    try:
        mysql_db.session.add(user)
        mysql_db.session.commit()
    except Exception as e:
        mysql_db.session.rollback()
        print("数据存储失败: ", e)
    else:
        print("用户设置成功")


def add_test_users():
    users = []
    now = datetime.datetime.now()
    for num in range(0, 10000):
        try:
            user = User()
            user.nick_name = "%011d" % num
            user.mobile = "%011d" % num
            user.password_hash = "pbkdf2:sha256:50000$SgZPAbEj$a253b9220b7a916e03bf27119d401c48ff4a1c81d7e00644e0aaf6f3a8c55829"
            user.last_login = now - datetime.timedelta(seconds=random.randint(0, 2678400))
            users.append(user)
            print(user.mobile)
        except Exception as e:
            print(e)
    with my_flask_app.app_context():
        mysql_db.session.add_all(users)
        mysql_db.session.commit()
    print('OK')


if __name__ == '__main__':
    # print(my_flask_app.url_map)
    # add_test_users()
    manager.run()
